'use strict'

const http=require('http');//动态导入，允许大小写

/** 
 * .jpg .jpeg ->image/jpeg
 * .png -> image/png
 * .gif -> image/gif
 * .ico -> image/x-icon
 * .txt -> image/plain  //text/plain 纯文本显示
 * .json-> image/json 或 application/json
 * .xml -> text/xml 或 application/xml
 */
let html=`
<!DOCTYPE html>
<html>
<head>
    <title>first-http</title>
</head>
<body>
    hello world!
    你好！
</body>
</html>
`

let routerTable={
    '/':async(request,response)=>{
        response.setHeader('Content-Type', 'text/html;charset=utf-8');
        response.end(html)
    },
    '/data':async(request,response)=>{
        let bufferList=[];
        let bufferlength=0;
        request.on('data',chunk=>{
            bufferlength+=chunk.length;
            bufferList.push(chunk);
        })
        let bodyData=null;
        request.on('end',()=>{
            if(bufferList.length>0){
                bodyData=Buffer.concat(bufferList,bufferlength);
                bufferList=[];
            }
            if(bodyData){
                response.end(bodyData)
            }else{
                response.end()
            }
        })
    },
    '/test':async(request,response)=>{
        let status=parseInt(Math.random()*200)+199;
        response.statusCode=status;
        response.end('test end');
    }

}

http.createServer((request,response)=>{

    if(!routerTable[request.url]){
        response.statusCode=404;
        response.end('page not found');
        return
    }
    routerTable[request.url](request,response)

    // let bufferList=[];
    // let bufferlength=0;
    // request.on('data',chunk=>{
    //     bufferlength+=chunk.length;
    //     bufferList.push(chunk);
    // })
    // let bodyData=null;
    // request.on('end',()=>{
    //     if(bufferlength>0){
    //         bodyData=Buffer.concat(bufferList,bufferlength);
    //         bufferList=[];
    //     }
    //     if(bodyData){
    //         response.end(bodyData);
    //     }else{
    //         response.setHeader('Content-Type', 'text/html;charset=utf-8');
    //         response.end(html)
    //     }
    // })



    // console.log(request);
    // response.end('ok');
    // response.setHeader('Content-Type', 'text/html;charset=utf-8');
    // response.end(html);

}).listen(3456)